//
//  CityDetailViewController.m
//  Funny
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 King. All rights reserved.
//

#import "CityDetailViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface CityDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,CityDeTailViewDelegate,ButtonViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) NSArray *dataArr;
@property (nonatomic, strong) UIImageView *backgroundImg; // 大背景
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSTimer *moveTime; // 城市足迹自动切换
@property (nonatomic, assign) NSInteger time;
@property (nonatomic, strong) CityDetailView *buttonView;
@property (nonatomic, strong) UIButton *mapButon;
@property (nonatomic, strong) ButtonView *cityBtn;
@property (nonatomic, strong) UILabel *name;
@property (nonatomic, strong) UILabel *nameE;
@property (nonatomic, strong) LocalWeatherView *weathView; // 存放天气的自定义view
@property (nonatomic, strong) CLLocationManager *locationManager; // 定位
@property (nonatomic, strong) NSDictionary *dic;

@end

@implementation CityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self location];
    [self handleData];
    [self.view addSubview:self.backgroundImg];
    
    UIImageView *location = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 25, 40, 50, 50)];
    location.image = [UIImage imageNamed:@"location2.png"];
    UIBlurEffect * blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView * effe = [[UIVisualEffectView alloc]initWithEffect:blur];
    effe.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [effe addSubview:self.scrollView];
    [self.view addSubview:effe];
    
    [_scrollView addSubview:location];
    [_scrollView addSubview:self.nameE];
    [_scrollView addSubview:self.name];
    [_scrollView addSubview:self.collectionView];
    [_scrollView addSubview:self.buttonView];
    [_scrollView addSubview:self.mapButon];
    [_scrollView addSubview:self.cityBtn];
    [_scrollView addSubview:self.weathView];
    
    // 城市足迹 标题
    UILabel *city = [[UILabel alloc]initWithFrame:CGRectMake(20, 605, 200, 30)];
    [self.scrollView addSubview:city];
    city.textColor = [UIColor whiteColor];
    city.text = @"城市足迹";
    
    // Do any additional setup after loading the view.
}

// 定位
- (void)location
{
    self.locationManager = [[CLLocationManager alloc] init] ;
    if([CLLocationManager locationServicesEnabled]) {
    }
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager requestAlwaysAuthorization];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

// 定位协议方法 得到定位城市
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations
{
    CLLocation *location = [[CLLocation alloc]init];
    location = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = placemarks[0];
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            [self handleDataForWeathWithCity:city];
        }
    }];
    [self.locationManager stopUpdatingLocation];
}

// 天气
- (LocalWeatherView *)weathView
{
    if (!_weathView) {
        _weathView = [[LocalWeatherView alloc]initWithFrame:CGRectMake(0, 421, ScreenWidth, 179)];
        _weathView.backgroundColor = [UIColor colorWithRed:0 / 256.0 green:0 / 256.0 blue:0 / 256.0 alpha:0.17];
    }
    return _weathView;
}

// 城市名字 国家
- (UILabel *)name
{
    if (!_name) {
        self.name = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 100, 110, 200, 30)];
        _name.font = [UIFont systemFontOfSize:19];
        _name.textColor = [UIColor whiteColor];
        _name.textAlignment = NSTextAlignmentCenter;
    }
    return _name;
}

// 城市英文名
- (UILabel *)nameE
{
    if (!_nameE) {
        _nameE = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 50, 150, 100, 30)];
        _nameE.font = [UIFont systemFontOfSize:19];
        _nameE.textColor = [UIColor whiteColor];
        _nameE.textAlignment = NSTextAlignmentCenter;
    }
    return _nameE;
}

// 城市介绍 热门推荐 自定义View
- (ButtonView *)cityBtn
{
    if (!_cityBtn) {
        _cityBtn = [[ButtonView alloc]initWithFrame:CGRectMake(0, 360, ScreenWidth, 60)];
        _cityBtn.backgroundColor = [UIColor colorWithRed:0 / 256.0 green:0 / 256.0 blue:0 / 256.0 alpha:0.17];
        _cityBtn.delegate = self;
    }
    return _cityBtn;
}

- (void)pushToNext
{
    CityIntroductionViewController *cityIVC = [CityIntroductionViewController shareViewController];
    cityIVC.cityID = self.ID;
    cityIVC.name = self.title;
    [self presentViewController:cityIVC animated:YES completion:^{
        
    }];
}

// push到热门景点页面
- (void)pushToRecommend
{
    MainRecommendViewController *mainVC = [MainRecommendViewController shareViewController];
    mainVC.ID = self.ID;
    [self.navigationController pushViewController:mainVC animated:NO];
}

// 调出地图页面
- (UIButton *)mapButon
{
    if (!_mapButon) {
        self.mapButon = [UIButton buttonWithFrame:CGRectMake(0, 722, ScreenWidth, ScreenWidth / 3 * 2) color:nil title:nil type:UIButtonTypeSystem target:self action:@selector(buttonWithBtn:) event:UIControlEventTouchUpInside cornerRadius:0];
    }
    return _mapButon;
}

- (void)buttonWithBtn:(UIButton *)btn
{
    MapViewController *mapVC = [MapViewController shareViewController];
    mapVC.longitude = [[_dic objectForKey:@"longitude"] floatValue];
    mapVC.latitude = [[_dic objectForKey:@"latitude"] floatValue];
    mapVC.name = self.title;
    [self.navigationController pushViewController:mapVC animated:NO];
}

// 大背景图 GET方法

-(UIImageView *)backgroundImg
{
    if (!_backgroundImg) {
        self.backgroundImg = [[UIImageView alloc]initWithFrame:self.view.bounds];
    }
    _backgroundImg.image = [UIImage imageNamed:@"earth.jpg"];
    return _backgroundImg;
}

// 覆盖在self.view的scrollView 将其他控件放在scrollView上可以滚动 GET方法

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, 980);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.userInteractionEnabled = YES;
        _scrollView.backgroundColor = [UIColor clearColor];
    }
    return _scrollView;
}

// 自定义View上的Button GET方法

- (CityDetailView *)buttonView
{
    if (!_buttonView) {
        self.buttonView = [[CityDetailView alloc]init];
        self.buttonView.frame = CGRectMake(0, 250, ScreenWidth, 109);
        self.buttonView.backgroundColor = [UIColor colorWithRed:0 / 256.0 green:0 / 256.0 blue:0 / 256.0 alpha:0.17];
        self.buttonView.userInteractionEnabled = YES;
        self.buttonView.delegate = self;
    }
    return _buttonView;
}

- (void)pushToNextWithType:(NSString *)type
{
    AnuseViewController *anuseVC = [AnuseViewController shareViewController];
    anuseVC.type = type; // 美食 购物 酒店 游玩 类型
    anuseVC.key = self.ID; // 城市id
    [self.navigationController pushViewController:anuseVC animated:NO];
}

// GET方法

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(ScreenWidth, 119);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 601, ScreenWidth, 119) collectionViewLayout:flowLayout];
        _collectionView.contentOffset = CGPointMake(ScreenWidth, 0);
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier:@"reuse" ];
        self.time = 0;
        [self moveTimeUp];
    }
    return _collectionView;
}

// 存放数据数组

- (NSArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}

#pragma mark - collectionView 协议方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:0 / 256.0 green:0 / 256.0 blue:0 / 256.0 alpha:0.17];
    cell.model = self.dataArr[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FootmarkViewController *footVC = [FootmarkViewController shareViewController];
    footVC.name = self.title;
    footVC.city_id = self.ID;
    [self.navigationController pushViewController:footVC animated:NO];
}

// 数据处理

- (void)handleData
{
    NSString *url = [NSString stringWithFormat:@"http://api.mxtrip.cn/api/area/getIndexData?&cityid=%@",self.ID];
    [NetHandler getDataWithURL:url completion:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.dataArr = [MainCityModel modelWithArr:[[dic objectForKey:@"data"] objectForKey:@"footprint"]];
        [self.mapButon sd_setBackgroundImageWithURL:[NSURL URLWithString:[[dic objectForKey:@"data"] objectForKey:@"map_pic"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_map.jpg"]];
        self.dic = [[[dic objectForKey:@"data"] objectForKey:@"geo"] firstObject];
        NSDictionary *areaDic = [[dic objectForKey:@"data"]objectForKey:@"area"];
        MainCityNameModel *nameModel = [MainCityNameModel modelWithDic:areaDic];
        self.title = nameModel.city_name;
        [self.backgroundImg sd_setImageWithURL:[NSURL URLWithString:nameModel.city_pic] placeholderImage:[UIImage imageNamed:@"earth.jpg"]];
        self.name.text = [NSString stringWithFormat:@"%@  ·  %@",nameModel.country_name,nameModel.city_name];
        self.nameE.text = nameModel.city_en_name;
        [self.collectionView reloadData];
    }];
}


// 天气数据处理
- (void)handleDataForWeathWithCity:(NSString *)city
{
    NSString *str = [NSString stringWithFormat:@"http://op.juhe.cn/onebox/weather/query?&key=5951a3f9026628976c93699f0d3f419a&cityname=%@",city];
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSDictionary *dic = data;
        if ([[dic objectForKey:@"result"] isEqual:[NSNull null]]) {
            self.weathView.cityName.text = @"暂不支持当前城市";
        }else{
            NSDictionary *dataDic = [[[dic objectForKey:@"result"] objectForKey:@"data"]objectForKey:@"realtime"];
            MainWeathModel *model = [MainWeathModel modelWithDic:dataDic];
            self.weathView.model = model;
            self.weathView.dic = [[[[dic objectForKey:@"result"] objectForKey:@"data"]objectForKey:@"life"] objectForKey:@"info"];
        }
        NSLog(@"@@@@@@@@");
    }];
}

// 控制collectionView的定时器方法

- (void)moveTimeUp
{
    self.moveTime = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(animalMoveImage) userInfo:nil repeats:YES];
}

- (void)animalMoveImage
{
    [self.collectionView setContentOffset:CGPointMake(ScreenWidth * self.time, 0) animated:YES];
    self.time++;
    if (self.time == _dataArr.count) {
        self.time = 0;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.locationManager.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.locationManager.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
